<template>
    <uni-forms :modelValue="formData" ref="form" class="st-uni-dynamic-form" :rules="rules">
        <template v-if="uniGroup">
            <template v-for="(groupItem,groupItemIndex) in formItems">
                <uni-group :title="groupItem.title"
                           :mode="groupItem.mode"
                           :top="groupItem.top" :key="groupItemIndex">
                    <template v-for="formItem in groupItem.formItems" v-if="!formItem.hidden">
                        <st-uni-dynamic-form-item :form-item="formItem" :form-data="formData"/>
                    </template>
                </uni-group>
            </template>
            <uni-group>
                <view class="st-uni-dynamic-form-btn">
                    <button type="primary" :loading="btnLoading" @tap="submitForm">{{buttonText}}</button>
                    <button v-if="resetButton" type="info" @tap="resetFields">重置</button>
                </view>
            </uni-group>
        </template>
        <template v-else>
            <uni-group>
                <template v-for="formItem in formItems" v-if="!formItem.hidden">
                    <st-uni-dynamic-form-item :form-item="formItem" :form-data="formData"/>
                </template>
                <view class="st-uni-dynamic-form-btn">
                    <button type="primary" :loading="btnLoading" @tap="submitForm">{{buttonText}}</button>
                    <button v-if="resetButton" type="info" @tap="resetFields">重置</button>
                </view>
            </uni-group>
        </template>
    </uni-forms>
</template>

<script>
    /**
     * uni-easyinput type :text/password/textarea(autoHeight)
     * DATE_PICKER type date/daterange/datetime/datetimerange
     */

    import StUniDynamicFormItem from './StUniDynamicFormItem'

    export default {
        name: 'StUniDynamicForm',
        components: {StUniDynamicFormItem},
        props: {
            formItems: {
                type: Array,
                default: function () {
                    return []
                }
            },
            buttonText: {
                default: '保存'
            },
            resetButton: {
                default: false
            },
            uniGroup: {
                default: false
            }
        },
        data() {
            return {
                formData: {},
                rules: {},
                btnLoading: false,
            }
        },
        onLoad() {
        },
        created() {
        },
        watch: {
            formItems: {
                handler: function (val, oldVal) {
                    this.initForm(val)
                },
                deep: true,
                immediate: true
            }
        },
        methods: {
            resetFields() {
                this.$refs.form.resetFields()
                if (this.formData) {
                    let _form = {}
                    Object.assign(_form, this.formData)
                    for (let key in _form) {
                        // let datePicker = this.formItems.filter(e => {
                        //     return key === e.name && e.eType === 'DATE_PICKER' && e.type === 'daterange'
                        // })
                        // this.$set(this.formData, key, datePicker && datePicker.length > 0 ? ['', ''] : null)
                        this.$set(this.formData, key, null)
                    }
                }
            },
            submitForm() {
                this.btnLoading = true
                this.$refs.form.validate().then(() => {
                    console.log('表单验证成功：', this.formData)
                    this.$emit('submit-form', this.formData)
                    this.btnLoading = false
                }).catch(err => {
                    console.log('表单错误信息：', err)
                    uni.showToast({
                        icon: 'none',
                        title: '请检查表单'
                    });
                    this.btnLoading = false
                })
            },
            initForm(e) {
                if (this.uniGroup) {
                    e.forEach(groupItem => {
                        groupItem.formItems.forEach(item => {
                            this.initFormItem(item)
                            this.initFormRules(item)
                        })
                    })
                } else {
                    e.forEach(item => {
                        this.initFormItem(item)
                        this.initFormRules(item)
                    })
                }
            },
            initFormItem(e) {
                this.$set(this.formData, e.name, e.value)
                //this.formData[e.name] = e.value || e.valueDefault || ''
            },
            initFormRules(e) {

                let rules = e.rules || {
                    rules: [{
                        required: e.required || false,
                        errorMessage: (e.eType === 'TEXT' ? '请输入' : '请选择') + (e.label || '')
                    }]
                }
                if (e.ruleType === 'mobile') {
                    //所以建议统一使用字符串的方式来使用正则 ，如'^\\S+?@\\S+?\\.\\S+?$' ，需要注意 \ 需要使用 \\ 来转译。
                    rules.rules.push({
                        pattern: '^(1[23456789]\\d{9})$',
                        errorMessage: "手机号格式不正确",
                        trigger: "change"
                    })
                }

                this.$set(this.rules, e.name, rules)
            }
        }
    }
</script>

<style>
    .st-uni-dynamic-form .checklist-group, .uni-data-checklist {
        margin-top: 5px !important;
    }

    .st-uni-dynamic-form-btn {
        display: flex;
    }

    .st-uni-dynamic-form-btn button {
        width: 100%;
    }
</style>
